package com.example.ftptest.util;

import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Component
public class FileManager {

    private static final String SLASH = "/";

    /**
     * 上传文件
     *
     * @param multipartFile 文件
     * @param type          类型
     * @param id            Id
     * @throws IOException
     */
    public String uploadFile(MultipartFile multipartFile, String type, String id
            , String children, FTPClient ftpClient) throws IOException {
        InputStream inputStream = null;
        String pathName = this.getPath(type, id, children);
        //判断地址是否存在，不存在则创建后进入
        if (!ftpClient.changeWorkingDirectory(pathName)) {
            String[] paths = pathName.split("/");
            for (String path : paths) {
                boolean a = ftpClient.makeDirectory(path);
                ftpClient.changeWorkingDirectory(path);
            }
        }
        try {
            inputStream = multipartFile.getInputStream();
            if (ftpClient.storeFile(multipartFile.getOriginalFilename(), inputStream))
                return pathName;
            throw new Exception("上传失败");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
        }
        return null;
    }

    /**
     * 下载文件
     *
     * @param path
     * @param res
     * @throws IOException
     */
    public void downloadFile(String path, HttpServletResponse res, FTPClient ftpClient) throws IOException {
        OutputStream outputStream = null;
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + path.substring(path.lastIndexOf("/")+1));
        try {
            outputStream = res.getOutputStream();
            ftpClient.retrieveFile(path, outputStream);
        } finally {
            outputStream.close();
        }
    }

    /**
     * 显示目录所有文件
     *
     * @param path
     * @param ftpClient
     * @return
     * @throws IOException
     */
    public FTPFile[] showFile(String path, FTPClient ftpClient) throws IOException {
        ftpClient.changeWorkingDirectory(path);
        FTPFile[] ftpFiles = ftpClient.listFiles();
        return ftpFiles;
    }

    /**
     * 删除文件
     *
     * @param path
     * @return
     * @throws IOException
     */
    public boolean deleteFile(String path, FTPClient ftpClient) throws IOException {
        return ftpClient.deleteFile(path);
    }

    /**
     * 创建文件夹
     *
     * @throws IOException
     */
    public boolean newDirectory(String pathName, FTPClient ftpClient) throws IOException {
        return ftpClient.makeDirectory(pathName);
    }

    /**
     * 删除指定目录
     *
     * @return
     */
    public boolean deleteDirectory(String pathName, FTPClient ftpClient) throws IOException {
        FTPFile[] files = ftpClient.listFiles(pathName);
        boolean flag = false;
        for (FTPFile f : files) {
            String path = pathName + File.separator + f.getName();
            if (f.isFile()) {
                ftpClient.deleteFile(path);
            } else if (f.isDirectory())
                deleteDirectory(path, ftpClient);
        }
        FTPFile[] files2 = ftpClient.listFiles(pathName);
        if (files2.length == 0)
            flag = ftpClient.removeDirectory(pathName);
        return flag;
    }

    /**
     * 删除空目录
     *
     * @param pathName
     * @return
     * @throws IOException
     */
    public boolean deleteEmptyDirectory(String pathName, FTPClient ftpClient) throws IOException {
        return ftpClient.removeDirectory(pathName);
    }

    /**
     * 进入某个目录
     *
     * @param directory
     * @throws IOException
     */
    public void changeWorkingDirectory(String directory, FTPClient ftpClient) throws IOException {
        ftpClient.changeWorkingDirectory(directory);
    }

    /**
     * 返回上一级目录
     *
     * @throws IOException
     */
    public void changeToParentDirectory(FTPClient ftpClient) throws IOException {
        ftpClient.changeToParentDirectory();
    }

    /**
     * 文件重命名
     *
     * @param oldFileName 旧文件名
     * @param newFileName 新文件名
     */
    public boolean renameFile(String oldFileName, String newFileName, FTPClient ftpClient) throws IOException {
        return ftpClient.rename(oldFileName, newFileName);
    }

    /**
     * 文件路径
     *
     * @param type
     * @param id
     * @return
     */
    public String getPath(String type, String id, String children) {
        return new StringBuilder(SLASH).append(this.Sting2String(type)).append(SLASH)
                .append(id).append(SLASH)
                .append(children).append(SLASH)
                .toString();
    }

    /**
     * 类型转换
     *
     * @param type
     * @return
     */
    private String Sting2String(String type) {
        switch (type) {
            case "0":
                return "house";
            case "1":
                return "estate";
            case "2":
                return "store";
            case "3":
                return "broker";
            default:
                throw new IllegalArgumentException();
        }
    }
}
